/**
 * @Copyright 2012, Founder Mobile Media Technology（Chongqing） Co., Ltd L.P. All
 *            rights reserved. The information contained herein is confidential
 *            and proprietary to Founder Mobile Media Technology（Chongqing） Co.,
 *            Ltd, and considered a trade secret as defined under civil and
 *            criminal statutes. Founder Mobile Media Technology（Chongqing） Co.,
 *            Ltd shall pursue its civil and criminal remedies in the event of
 *            unauthorized use or misappropriation of its trade secrets. Use of
 *            this information by anyone other than authorized employees of
 *            Founder Mobile Media Technology（Chongqing） Co., Ltd is granted
 *            only under a written non-disclosure agreement, expressly
 *            prescribing the scope and manner of such use.
 */
package com.g2room.bytes;

import java.io.UnsupportedEncodingException;


/**
 * 
 *
 * @createTime: Jun 13, 2013 3:52:49 PM
 * @author: <a href="mailto:gaoxg@FOUNDER.COM.CN">Xuguo Gao</a>
 * @version: 0.1
 * @lastVersion: 0.1
 * @updateTime: 
 * @updateAuthor: <a href="mailto:gaoxg@FOUNDER.COM.CN">Xuguo Gao</a>
 * @changesSum: 
 * 
 */
public class TestBytes {
	public static final String CHARSET_UCS2 = "UTF-16BE";
	
	//长短信头信息
	public static final byte[] MSG_HEAD = { 0x05, 0x00, 0x03, 0x00, 0x00, 0x00};
	
	public static int LENGTH_MSG_HEAD = MSG_HEAD.length;
	
	public static int SMSMAXLENGTH = 138;

	// ucs2编码
    
//	static {
////		ResourceManager rm = ResourceManager.getInstance();
//		SMSMAXLENGTH = StringUtils.getDefaultValue(rm.getValue("sms.parameter.maxlength"),139);
//		System.out.println("SMSMAXLENGTH:" + SMSMAXLENGTH +" in "+LongSMSEncode.class);
//	}

	//最大短信内容长度
	public static final int MaxExtBodyLen = SMSMAXLENGTH - LENGTH_MSG_HEAD;

    public static byte[][] enCodeBytes(String longSMS) {

        byte dlDataByte[] = null;
        try {
            dlDataByte = longSMS.getBytes(CHARSET_UCS2);
        } catch (Exception e) {
        	System.out.println(e.getMessage());
        }
        return getMultiSMSBinaryData(dlDataByte,getId());
    }

    /**
     * 分拆一条wappush二进制数据为符合长度要求的若干条二进制数据
     * 
     * @return 若干条二进制数据
     */
    private static byte[][] getMultiSMSBinaryData(byte[] oneBigSMS,byte longSMSID) {
        System.out.println("***************getMultiSMSBinaryData begin*************");
        // byte[] oneBigSMS = GetSMSBinaryData();
        System.out.println("oneBigSMS.length  = " + oneBigSMS.length);
        byte[][] results;
        // 需要对刚好整除情况处理，所以用ceil（）表示上约，注意ceil（）需要传入double参数才能得到正确结果
        int totalSMSAmount = (oneBigSMS.length <= SMSMAXLENGTH) ? 1
                : ((int) Math.ceil((double) (oneBigSMS.length) / MaxExtBodyLen));
        // ((oneBigSMS.length-UDH_LENGTH) / (SMSMAXLENGTH-UDH_EXT_LENGTH) + 1);
        System.out.println("totalSMSAmount  = " + totalSMSAmount);
        results = new byte[totalSMSAmount][]; // a SMS per row
        // 单包
        if (totalSMSAmount == 1) {
            System.out.println("Single SMS Packet, packet length is : "
                    + oneBigSMS.length);
            results[0] = new byte[oneBigSMS.length+LENGTH_MSG_HEAD];
            //results[0] = oneBigSMS;
            fillHead(results[0], 1, 1,longSMSID);
            System.out.println("============" + LENGTH_MSG_HEAD);
            System.arraycopy(oneBigSMS, 0, results[0], LENGTH_MSG_HEAD, oneBigSMS.length);
            // fillBody(oneBigSMS, 0, results[0], 0, oneBigSMS.length);
            System.out.println("*************Single SMS Packet finished ************"+results[0].length);
            return results;
        }
        // 多包
        for (int j = 0; j < totalSMSAmount; j++) {
            // 根据是否最后一个包判定包长度
            int length = (j != (totalSMSAmount - 1)) ? SMSMAXLENGTH
                    : (oneBigSMS.length - MaxExtBodyLen * j + LENGTH_MSG_HEAD);
            System.out.println("length of SMS packet [ " + j + " ] is " + length);
            results[j] = new byte[length];
            fillHead(results[j], totalSMSAmount, j + 1,longSMSID);
            System.arraycopy(oneBigSMS, MaxExtBodyLen * j, results[j],
                    LENGTH_MSG_HEAD, length - LENGTH_MSG_HEAD);
            //ByteTool.printHex(results[j], log);
        }
        System.out.println("*******************getMultiSMSBinaryData finished.(Multiple SMS packet) ****************");
        return results;
    }

    private static byte longSMSID = 0;
    private synchronized static byte getId() {
    	if(++longSMSID>=Byte.MAX_VALUE)
    		longSMSID=0;
    	return longSMSID;
    }
    private static void fillHead(byte[] result, int totalSMSAmount, int number,byte longSMSID) {
        System.out.println("*******************fillUDH begin*******************");
        if ((number > totalSMSAmount) || (number <= 0)) {
            System.out.println("can't generate UDH correctly.");
        }
        
        //MSG_HEAD
        System.arraycopy(MSG_HEAD, 0, result, 0, LENGTH_MSG_HEAD); // 固定的长短信消息头
        result[LENGTH_MSG_HEAD - 3] = longSMSID; // 长短信参考号
        result[LENGTH_MSG_HEAD - 2] = (byte) totalSMSAmount; // 长短信消息总条数
        result[LENGTH_MSG_HEAD - 1] = (byte) number; // 长短信消息序号
        
        System.out.println("*******************fillUDH finished*******************");
    }

	public static void main(String[] args) {
//		String str = "ssssssssss;ss1123ewssssss;测试testsssssssssssssss;测试testsssssssssssssss";
		String str = "ssssssswssssss;测试testsssssssssssssss;测试testsssssssssssssss";
		System.out.println("========="+str.length());
		byte[][] s= enCodeBytes(str);
		System.out.println("*********"+s.length);
		for(byte[] b: s) {
			System.out.println("======"+b.length);
			try {
				System.out.println(new String(b, CHARSET_UCS2));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
